package com.yuanxiao.config;

import com.yuanxiao.pojo.Configuration;
import com.yuanxiao.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration=configuration;
    }
    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace=rootElement.attributeValue("namespace");
        List<Element> select = rootElement.selectNodes("//select");
        setMappedStatement(select,namespace,"select");
        List<Element> insert = rootElement.selectNodes("//insert");
        setMappedStatement(insert,namespace,"insert");
        List<Element> delete = rootElement.selectNodes("//delete");
        setMappedStatement(delete,namespace,"delete");

        List<Element> update = rootElement.selectNodes("//update");
        setMappedStatement(update,namespace,"update");

    }
    public void setMappedStatement(List<Element> list,String namespace,String sqlType){
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sqlTrim = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setSql(sqlTrim);
            mappedStatement.setSqlType(sqlType);
            String key=namespace+"."+id;
            configuration.getMappedStatementMap().put(key,mappedStatement);
        }
    }
}
